package com.smxy.daydayup.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.smxy.daydayup.util.file.UploadGiteeImgBed;
import com.smxy.daydayup.util.result.ResultUtil;
import com.smxy.daydayup.util.result.ReturnResult;
import com.smxy.daydayup.util.result.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @team daydayup
 * @time 2021-12-13 8:40
 */

@RestController
@RequestMapping("/file")
@Api(tags = "文件上传控制器")
public class FileUploadController {


    @ApiOperation("文件回显接口")
    @GetMapping("/showImg")
    public void ioReadImg(HttpServletResponse response){
        try {
            response.getWriter().write(111);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("上传图片接口")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ReturnResult uploadCover(@ApiParam(value = "图片",required = true) @RequestPart @RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();

            String targetURL = UploadGiteeImgBed.createUploadFileUrl(fileName);
            Map<String, Object> uploadBodyMap = UploadGiteeImgBed.getUploadBodyMap(file.getBytes());
            String JSONResult = HttpUtil.post(targetURL, uploadBodyMap);
            JSONObject jsonObj = JSONUtil.parseObj(JSONResult);
            if(jsonObj == null || jsonObj.getObj("commit") == null){
                return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"上传失败");
            }
            JSONObject content = JSONUtil.parseObj(jsonObj.getObj("content"));
            return ResultUtil.returnSuccess(content.getObj("download_url"),"上传成功");
        } catch (Exception e) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"上传失败");
        }
    }
}
